﻿// ===============================================================================
// For .NET 2.0
//
// File :         BasicPage.cs
// Date :         2009-10-28
// Decription :   基础页，页面的共有代码都写于此
// Author:        duyi
// 其他信息:
// ===============================================================================
// 版本变更记录
// Version Decription
//   1.0  	
// ===============================================================================
// 公司名称:JCPX
// ===============================================================================
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Elota.SCAQGL.Models;
using Elota.SCAQGL.BLL;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using Elota.SCAQGL.CommandTools;
using System.Security.Cryptography;
using System.Text;


/// <summary>
///   基础页，页面的共有代码都写于此
/// </summary>
public class BasicPage : System.Web.UI.Page
{
    /// <summary>
    /// 页面加载时候验证是否登陆 没有登陆则返回到登陆页面
    /// </summary>
    /// <param name="e"></param>
    protected override void OnLoad(EventArgs e)
    {
        //方便开发是测试，暂时注释
        //if (Session["UserID"] == null)
        //{
            //Response.Write("<script>window.parent.location.href='../login.html';</script>");

        //}
        base.OnLoad(e);
    }
   /// <summary>
    /// 获取页面完整路径
    /// </summary>
    /// <param name="strUrl"></param>
    /// <returns></returns>
    protected string GetFullPath(string strUrl)
    {
        string sFullPath = this.Server.MapPath(strUrl);//要跳转的页面地址
        sFullPath = sFullPath.Replace(this.Server.MapPath("~"), "");
        sFullPath = sFullPath.Replace("\\", "/");
        string sCurrPath = this.Server.MapPath("");
        sCurrPath = sCurrPath.Replace(this.Server.MapPath("~"), "");
        string[] str = sCurrPath.Split('\\');
        for (int i = 0; i < str.GetLength(0); i++)
        {
            if (str[i] != "")
                sFullPath = "../" + sFullPath;
        }
        sFullPath = sFullPath.Replace("//", "/");
        if (sFullPath.IndexOf("..").Equals(-1))
            sFullPath = sFullPath.Remove(0, 1);
        return sFullPath;
    }
    /// <summary>
    /// 到指定的页面
    /// </summary>
    /// <param name="page"></param>
    /// <param name="strUrl"></param>
    protected void GoPage(Page page, string strUrl)
    {
        strUrl = this.Page.ResolveClientUrl(strUrl);
        this.Response.Redirect(strUrl);
        //page.Response.Redirect(strUrl);
        // strUrl = GetFullPath(strUrl);
        //page.ClientScript.RegisterStartupScript(page.GetType(), "gotopage", "<script language='javascript' defer>try{window.open('" + strUrl + "');}catch(err){}</script>");
    }
   
    /// <summary>
    /// 构造函数
    /// </summary>
    public BasicPage()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    /// <summary>
    /// 生成JavaScript 提示提示脚本
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public String GetDeleteJsString(string text)
    {
        String sJs = "return confirm('" + text + "');";
        return sJs;
    }
   
    /// <summary>
    /// 显示提示信息
    /// </summary>
    /// <param name="text">提示框显示的文本</param>
    /// <param name="strUrl">提示框确定后跳转的页面地址</param>
    /// <returns></returns>
    public void ShowMessage(Page page, string text)
    {
        String sJs = "<script language='javascript'>alert('" + text + "')</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(),"MessageJs",sJs);
    }
    public void ShowMessage(Page page, string text, string strUrl)
    {
        String sJs = "<script language='javascript'>alert('" + text + "');window.location.href='" + strUrl + "'</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "MessageJs", sJs);
        //Page.RegisterStartupScript(null, sJs);
    }
    /// <summary>
    /// 生成页面记录消息
    /// </summary>
    /// <param name="iPageCount"></param>
    /// <param name="iSize"></param>
    /// <param name="iIndex"></param>
    /// <param name="iCount"></param>
    /// <returns></returns>
    public string GetCurrentPageInfo(int iPageCount, int iIndex, int iCount)
    {
        string sPageInfo = "总共：" + iPageCount.ToString() + " 条数据  页数： " + (iIndex + 1).ToString() + "/" + iCount.ToString();
        return sPageInfo;
    }
    /// <summary>
    /// 将日期转换为字符串 如果时间为 DateTime.MaxValue 则返回空
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    protected string ConvertDateTime(object obj)
    {
        string result = "";
        DateTime dt = Convert.ToDateTime(obj);
        result = dt.ToString("yyyy-MM-dd").Equals(DateTime.MaxValue.ToString("yyyy-MM-dd")) ? "" : dt.ToString("yyyy-MM-dd");
        return result;
    }
    /// <summary>
    /// 将日期转换为字符串 如果时间为 DateTime.MaxValue 则返回空
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    protected string ConvertDateAndTime(object obj)
    {
        string result = "";
        DateTime dt = Convert.ToDateTime(obj);
        result = dt.ToString("yyyy-MM-dd").Equals(DateTime.MaxValue.ToString("yyyy-MM-dd")) ? "" : dt.ToString("yyyy-MM-dd HH:mm");
        return result;
    }
    /// <summary>
    /// 将字符转换为浮点型
    /// </summary>
    /// <param name="oj"></param>
    /// <returns></returns>
    protected float ConvertToFloat(object oj)
    {
        float fResult;
        bool result = float.TryParse(oj.ToString(), out fResult);
        fResult = result ? fResult : 0;
        return fResult;
    }
    /// <summary>
    /// 将字符转换为double型
    /// </summary>
    /// <param name="oj"></param>
    /// <returns></returns>
    protected double ConvertToDouble(object oj)
    {
        double dResult;
        bool result = double.TryParse(oj.ToString(), out dResult);
        dResult = result ? dResult : 0;
        return dResult;
    }
    /// <summary>
    /// 将字符转换为 Int
    /// </summary>
    /// <param name="oj"></param>
    /// <returns></returns>
    protected int ConvertToInt(object oj)
    {
        int iResult;
        bool result = int.TryParse(oj.ToString(), out iResult);
        iResult = result ? iResult : 0;
        return iResult;
    }
    
    #region 上传图片
    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="FU"></param>
    /// <param name="hotelImage"></param>
    /// <returns></returns>
    protected string FUImage(FileUpload FU, string hotelImage)
    {
        if (FU.PostedFile.FileName != "")
        {
            string msg = null;//上传图片失败提示消息
            string uppath = Server.MapPath("~/FileUpload/images/");
            string uppath_teum = Server.MapPath("~/FileUpload/Images_thum/");//缩略图地址
            int teumWidth = 120;
            int teumHeight = 80;

            FileInfo info = new FileInfo(FU.FileName);

            string ext = info.Extension;
            int imgLength = FU.PostedFile.ContentLength;
            if (ext.ToUpper() == ".JPG" || ext.ToUpper() == ".PNG" || ext.ToUpper() == ".GIF" || ext.ToUpper() == ".BMP")
            {
                if (imgLength <= 2048000)
                {

                    //原始图片名称
                    string OldImageName = hotelImage;

                    if (!System.IO.Directory.Exists(uppath))//如果目标不存在则创建
                        System.IO.Directory.CreateDirectory(uppath);
                    if (!System.IO.Directory.Exists(uppath_teum))//如果目标不存在则创建
                        System.IO.Directory.CreateDirectory(uppath_teum);

                    string strFullName = DateTime.Now.ToString("yyyyMMddHHmmss") + "0001" + ext;
                    string strFullPath = uppath + strFullName;
                    int i = 1;
                    while (File.Exists(strFullPath))
                    {
                        i++;
                        strFullName = DateTime.Now.ToString("yyyyMMddHHmmss") + i.ToString("0000") + ext;
                        strFullPath = uppath + strFullName;
                    }
                    try
                    {
                        FU.SaveAs(strFullPath);
                        info = new FileInfo(strFullPath);
                        hotelImage = info.Name;
                        Console.WriteLine(info.Name);
                        CreateThumbnail(teumWidth, teumHeight, strFullPath, uppath_teum + strFullName);
                        if (OldImageName != "")
                        {
                            if (File.Exists(uppath + OldImageName)) File.Delete(uppath + OldImageName);//如果存在则删除原始图片
                            if (File.Exists(uppath_teum + OldImageName)) File.Delete(uppath_teum + OldImageName);//如果存在则删除缩略图
                        }

                    }
                    catch (Exception ex)
                    {
                        Response.Write(ex);
                    }
                }
                else 
                {
                    msg = string.Format("上传图片<<{0}>>失败，上传图片限制单张最大为2048K", FU.FileName);
                    ShowMessage(this, msg);
                }
              
            }
            else
            {
                msg = string.Format("上传图片<<{0}>>失败，只能上传(.jpg|.png|.gif|.bmp)格式的文件", FU.FileName);
                ShowMessage(this, msg);
            }
        }
        else
        {
            return hotelImage;
        }
        return hotelImage;

    }
    #endregion


    
    /// <summary>
    ///  生产文件全路径
    /// </summary>
    /// <returns></returns>
    protected string GetFileName(string strExt, string saveUrl)
    {
        string strPath = this.Server.MapPath(saveUrl);
        if (!System.IO.Directory.Exists(strPath))//如果目标不存在则创建
            System.IO.Directory.CreateDirectory(strPath);

        string strFullName = strPath + DateTime.Now.ToString("yyyyMMddHHmmss") + "0001" + strExt;
        int i = 1;
        while (File.Exists(strFullName))
        {
            i++;
            strFullName = strPath + DateTime.Now.ToString("yyyyMMddHHmmss") + i.ToString("0000") + strExt;
        }
        return strFullName;
    }

   
   
    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="str"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    private string Encode(string str, string key)
    {
        DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
        provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
        provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
        byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(str);
        MemoryStream stream = new MemoryStream();
        CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
        stream2.Write(bytes, 0, bytes.Length);
        stream2.FlushFinalBlock();
        StringBuilder builder = new StringBuilder();
        foreach (byte num in stream.ToArray())
        {
            builder.AppendFormat("{0:X2}", num);
        }
        stream.Close();
        return builder.ToString();
    }

    /// <summary>
    /// Des 解密 GB2312 
    /// </summary>
    /// <param name="str">Desc string</param>
    /// <param name="key">Key ,必须为8位 </param>
    /// <returns></returns>
    private string Decode(string str, string key)
    {
        DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
        provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
        provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
        byte[] buffer = new byte[str.Length / 2];
        for (int i = 0; i < (str.Length / 2); i++)
        {
            int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
            buffer[i] = (byte)num2;
        }
        MemoryStream stream = new MemoryStream();
        CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
        stream2.Write(buffer, 0, buffer.Length);
        stream2.FlushFinalBlock();
        stream.Close();
        return Encoding.GetEncoding("GB2312").GetString(stream.ToArray());
    }


    /// <summary>
    ///  加密传入的字符串
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public string Encrypt(object str)
    {
        return this.Encode(str.ToString(), "a1b2c3d4");//默认加KEY:a1b2c3d4
    }
    /// <summary>
    /// 解密传入的字符串
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public string Decrypt(object str)
    {
        return this.Decode(str.ToString(), "a1b2c3d4");
    }
    public bool IsSuperviseEdit()
    {
        if (Session["IsSuperviseEdit"] != null)
            return (bool)Session["IsSuperviseEdit"];
        else
            return false;
    }
    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="NewWidth">缩略图宽度</param>
    /// <param name="NewHeight">缩略图宽度</param>
    /// <param name="OldPath">原始图像地址</param>
    /// <param name="NewPath">保存图像地址</param>
    /// <returns></returns>
    #region 生成缩略图
    public static bool CreateThumbnail(int NewWidth, int NewHeight, string OldPath, string NewPath)
    {
        try
        {
            int oldwidth, oldheight, neww, newh;
            System.Drawing.Image image, newimage;
            System.Drawing.Image.GetThumbnailImageAbort callb = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            image = System.Drawing.Image.FromFile(OldPath);
            oldwidth = image.Width;
            oldheight = image.Height;
            if (oldwidth > oldheight)
            {
                neww = NewWidth;
                newh = oldheight * NewWidth / oldwidth;
            }
            else
            {
                newh = NewHeight;
                neww = oldwidth * NewHeight / oldheight;
            }
            newimage = image.GetThumbnailImage(neww, newh, callb, IntPtr.Zero);
            newimage.Save(NewPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            image.Dispose();
            return true;
        }
        catch
        {
            return false;
        }
    }
    private static bool ThumbnailCallback()
    {
        return false;
    }
    #endregion
}
